package com.ido.sms;

import com.alibaba.fastjson2.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 阿里云短信服务
 */
@Slf4j
@Data
@Service
public class AliyunSmsClient {

    @Autowired
    private Client client;
    @Autowired
    private AliyunSmsConfig smsConfig;

    /**
     * 阿里短信发送短信
     *
     * @param phoneNumber   手机号
     * @param templateCode  阿里模板Code
     * @param templateParam 模板内容参数 {"code":"{0}","time":"{1}"}
     * @return
     */
    public boolean sendSms(String phoneNumber, String templateCode, String templateParam) {
        log.info("短信-阿里云： 请求入参， signName【{}】 templateCode【{}】 templateParam【{}】"
                , smsConfig.getSignName(), templateCode, templateParam);
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setPhoneNumbers(phoneNumber)
                .setSignName(smsConfig.getSignName())
                .setTemplateCode(templateCode)
                .setTemplateParam(templateParam);

        try {
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            Integer httpCode = sendSmsResponse.getStatusCode();
            log.info("短信-阿里云： 请求结果， sendSmsResponse【{}】", JSON.toJSONString(sendSmsResponse));
            SendSmsResponseBody body = sendSmsResponse.getBody();
            if (Objects.nonNull(body) && "OK".equalsIgnoreCase(body.getCode())) {
                return true;
            } else {
                log.warn("短信-阿里云：发送失败，phone【{}】,httpCode【{}】,body【{}】:", phoneNumber, httpCode, JSON.toJSONString(body));
                return false;
            }
        } catch (Exception ex) {
            log.error("短信-阿里云：发送异常，phone【{}】,ex:", phoneNumber, ex);
            return false;
        }
    }


}
